import Client from 'jsftp'
import FtpConfig from '@/models/FtpConfig'
import moment from 'moment'
export class FtpUtil {
    public connected: boolean = false;
    private ftp?: Client;
    private config: FtpConfig

    constructor(config: FtpConfig) {
        this.config = config;
    }
    public saveToFtp(buffer: Buffer) {
        return new Promise((resolve, reject) => {
            if (!this.ftp) {
                this.ftp = new Client({
                    host: this.config.ftpHost,
                    port: this.config.ftpPort,
                    user: this.config.ftpUsername,
                    pass: this.config.ftpPassword
                });
                let fileName = this.config.fileName;
                if (fileName === '') {
                    let timeStr = moment().format('YYYYMMDDHHmmss');
                    fileName = 'ftp_all_' + timeStr + '.lowdb';
                } else {
                    fileName += ".lowdb";
                }
                this.ftp.put(buffer, this.config.remoteDir + fileName, (err) => {
                    this.closeConnection();
                    if (err) {
                        return reject(err);
                    } else {
                        resolve();
                    }
                })
            } else {
                return reject(new Error("上一个FTP连接还没有关闭"))
            }
        })
    }
    public testConnection() {
        return new Promise((resolve, reject) => {
            this.ftp = new Client({
                host: this.config.ftpHost,
                port: this.config.ftpPort,
                user: this.config.ftpUsername,
                pass: this.config.ftpPassword
            });
            this.ftp.auth(this.config.ftpUsername, this.config.ftpPassword, (err, res) => {
                if (err) {
                    return reject(err);
                } else {
                    this.closeConnection();
                    resolve();
                }
            })
        })
    }
    private closeConnection() {
        if (this.ftp) {
            this.ftp.destroy();
            this.ftp = undefined;
        }
    }
}